package com.zc58s.springbootmqtt.mqtt;

import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @author : fujc-dev@qq.com
 * @created : 2022/9/26 10:11
 */
public class MqttFactory {

    private static MqttFactory factory;
    private static MqttClient client = null;

    private MqttFactory() {

    }

    public static MqttFactory get() {
        if (factory == null) {
            synchronized (MqttFactory.class) {
                factory = new MqttFactory();
            }
        }
        return factory;
    }

    public void initMqtt() {

    }

    public void connect(String username, String password) {
        try {
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(2);
            options.setKeepAliveInterval(10);
            client.connect(options);
            System.out.println("MQTT连接：" + client.isConnected());
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}
